package com.basic.business.goodsLabel.service.impl;

import cn.idev.excel.EasyExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import cn.idev.excel.util.ListUtils;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.goodsLabel.domain.TGoodsLabel;
import com.basic.business.goodsLabel.service.ITGoodsLabelService;
import com.basic.business.goodsLabel.mapper.TGoodsLabelMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 商品标签管理Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TGoodsLabelServiceImpl extends BaseServiceImpl<TGoodsLabelMapper,TGoodsLabel> implements ITGoodsLabelService {

    @Resource
    private TGoodsLabelMapper tGoodsLabelMapper;


    @Override
    public int saveOrUpdate(TGoodsLabel tGoodsLabel) {
        return tGoodsLabelMapper.saveOrUpdate(tGoodsLabel);
    }

    @Transactional
    @Override
    public void importFileData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), TGoodsLabel.class, new ReadListener<TGoodsLabel>() {

                /**
                 * 单次缓存的数据量
                 */
                public static final int BATCH_COUNT = 500;
                /**
                 *临时存储
                 */
                private List<TGoodsLabel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

                @Override
                public void invoke(TGoodsLabel tGoodsLabel, AnalysisContext analysisContext) {
                    cachedDataList.add(tGoodsLabel);
                    if (cachedDataList.size() >= BATCH_COUNT) {
                        tGoodsLabelMapper.saveBatch(cachedDataList);
                        // 存储完成清理 list
                        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    tGoodsLabelMapper.saveBatch(cachedDataList);
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("文件数据导入失败！",e);
        }
    }
}
